package com.lagou.rpc.consumer.processor;

import com.lagou.rpc.consumer.anno.RpcReference;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 对bean初始化之后进行bean方法代理操作
 */
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Autowired
    private RpcClientProxy rpcClientProxy;

    /**
     * bean初始化方法调用前被调用
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // TODO Auto-generated method stub
        System.out.println("postProcessBeforeInitialization..." + beanName + "=>" + bean);
        return bean;
    }

    /**
     * bean初始化方法调用后被调用
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // TODO Auto-generated method stub
        System.out.println("postProcessAfterInitialization..." + beanName + "=>" + bean);
        Class<?> aClass = bean.getClass();
        //获取所有的属性名
        Field[] declaredFields = aClass.getDeclaredFields();
        for(Field field:declaredFields){
            //判断是否带RPCService标签
            if(field.getAnnotation(RpcReference.class)!=null){
                //带RPCService的service接口
                Object proxy = rpcClientProxy.createProxy(field.getType());
                try {
                    //开启强制
                    field.setAccessible(true);
                    //把代理后的bean信息赋值
                    field.set(bean, proxy);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return bean;
    }

}